package com.briup.pai.listener;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.briup.pai.common.constant.ModelConstant;
import com.briup.pai.common.enums.ModelStatusEnum;
import com.briup.pai.convert.ReleaseConvert;
import com.briup.pai.entity.message.ModelReleaseResultMessage;
import com.briup.pai.entity.po.Model;
import com.briup.pai.entity.po.Release;
import com.briup.pai.service.IModelService;
import com.briup.pai.service.IReleaseService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
@CacheConfig(cacheNames = ModelConstant.MODEL_CACHE_PREFIX)
public class ModelReleaseRabbitListener {

    @Autowired
    private IReleaseService releaseService;
    @Autowired
    private IModelService modelService;

    @Autowired
    private ReleaseConvert releaseConvert;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${mq.release.result-queue}", durable = "true"),
            exchange = @Exchange(value = "${mq.release.exchange}"),
            key = "${mq.release.result-routing-key}"
    ))
    @Transactional
    public void receiveReleaseMessage(String message) {
        ModelReleaseResultMessage resultMessage = JSON.parseObject(message, ModelReleaseResultMessage.class);
        ((ModelReleaseRabbitListener) AopContext.currentProxy()).processReleaseResult(resultMessage);
    }

    @Transactional
    @CacheEvict(key = "T(com.briup.pai.common.constant.CommonConstant).DETAIL_CACHE_PREFIX+':'+#modelId")
    public void processReleaseResult(ModelReleaseResultMessage resultMessage){
        // 判断是发布成功还是取消发布
        if(ObjectUtil.equals(resultMessage.getModelStatus(), ModelStatusEnum.Published.getStatus())){
            // 添加一条发布的记录
            Release release = releaseConvert.modelReleaseResultMessage2Po(resultMessage);
            release.setCreateTime(new Date());
            releaseService.save(release);
        }else {
            // 删除一条发布记录
            LambdaQueryWrapper<Release> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Release::getModelId, resultMessage.getModelId());
            releaseService.remove(lqw);
        }
        // 更新模型的状态
        Model model = modelService.getById(resultMessage.getModelId());
        model.setModelStatus(resultMessage.getModelStatus());
        modelService.updateById(model);
    }
}
